from django.contrib import admin

from .models import Category, Tag, Album, Photo
from django.utils.html import format_html


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'description')
    search_fields = ('name',)
    ordering = ('name',)


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)


class PhotoInline(admin.TabularInline):
    model = Photo
    extra = 1
    readonly_fields = ['image_preview','uploaded_at']
    fields = ['title', 'image', 'image_preview', 'description', 'category', 'tags', 'uploaded_at']
    show_change_link = True

    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="height: 60px;" />', obj.image.url)
        return ""

    image_preview.short_description = "预览图"


@admin.register(Album)
class AlbumAdmin(admin.ModelAdmin):
    list_display = ('title', 'owner', 'created_at')
    search_fields = ('title', 'owner__username')
    list_filter = ('created_at',)
    inlines = [PhotoInline]


@admin.register(Photo)
class PhotoAdmin(admin.ModelAdmin):
    list_display = ('title', 'album', 'uploaded_by', 'category', 'uploaded_at', 'image_preview')
    list_filter = ('category', 'tags', 'album', 'uploaded_by')
    search_fields = ('title', 'description', 'uploaded_by__username')
    readonly_fields = ['image_preview']
    autocomplete_fields = ['tags', 'category', 'album']
    filter_horizontal = ['tags']

    def image_preview(self, obj):
        if obj.image:
            return format_html('<img src="{}" style="height: 60px;" />', obj.image.url)
        return ""

    image_preview.short_description = "预览图"
